package com.ajie.component;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/socket1/{id}")
@Component
public class WebSocketServer {
    
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    
    /**
     * 记录当前在线连接处
     */
    public static final Map<Long, Session> sessionMap = new ConcurrentHashMap<>();
    
    
    /**
     *
     */
    
    @OnOpen
    public void onOpen(Session session, @PathParam("id") Long id) throws InterruptedException {
        sessionMap.put(id,session);
        log.info("有用户加入，id={},当前在线人数为：{}",id,sessionMap.size());
        JSONObject result = new JSONObject();
        JSONArray array = new JSONArray();
        result.set("users",array);
        for (Object key : sessionMap.keySet()){
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("id",key);
            array.add(jsonObject);
        }
        Session toSession = sessionMap.get(id);
        this.sendMessage("1111111111",toSession);
        sendAllMessage(JSONUtil.toJsonStr(result));//发送给所有的客户端
    }
    
    @OnClose
    public void onClose(Session session,@PathParam("id") Long id){
        sessionMap.remove(id);
        log.info("有一链接关闭，移除id={}的用户session，当前在线人数为，{}",id,sessionMap.size());
    }
    
    
    @OnMessage
    public void onMessage(String message,Session session,@PathParam("id") Long id){
        log.info("服务端收到客户发来的消息{}",message);
        if ("heartBath".equals(message)){
            Session toSession = sessionMap.get(id);
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("text","socket连接正常");
            this.sendMessage(jsonObject.toString(),toSession);
        }else {
            JSONObject obj = JSONUtil.parseObj(message);
            Long toId = obj.getLong("to");
            String text = obj.getStr("text");
            Session toSession = sessionMap.get(toId);
            if (toSession != null){
                JSONObject jsonObject = new JSONObject();
                jsonObject.set("from",id);
                jsonObject.set("text",text);
                this.sendMessage(jsonObject.toString(),toSession);
                log.info("发送给用户id={},消息：{}",toId,jsonObject.toString());
            }else {
                log.info("发送消息失败,未找到用户id={}的session",toId);
            }
        }
        
    }
    
    @OnError
    public void onError(Throwable error){
        log.info("发生错误");
        error.printStackTrace();
    }
    
    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端{}发送消息{}",toSession.getId(),message);
            toSession.getBasicRemote().sendText(message);
        }catch (Exception e){
            log.info("服务端给客户端发送消息失败",e);
        }
        
    }
    
    
    public void sendAllMessage(String message){
        try {
            for (Session session: sessionMap.values()){
                log.info("服务端给客户端{}发送消息{}",session.getId(),message);
                session.getBasicRemote().sendText(message);
            }
        }catch (Exception e){
            log.info("服务端给客户端发送消息失败",e);
        }
    }

}
